package com.im.interceptor;

import com.im.entity.vo.UserInfoVO;
import com.im.service.IImUserService;
import com.im.utils.TokenUtil;
import com.im.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * JWT 认证拦截器
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenUtil tokenUtil;

    @Autowired
    private IImUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
         // 获取 Token
        log.info("url{}",request.getRequestURI());
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (token == null || !token.startsWith("Bearer ")) {
            log.warn("❌ 认证失败：缺少 Token——{}",request.getRequestURI());
//            throw new RuntimeException("认证失败：缺少 Token");
        }

        // 解析 Token
        token = token.replace("Bearer ", "");
        Integer userId = tokenUtil.getUserIdFromToken(token);
        if (userId == null || !tokenUtil.validateToken(token)) {
            log.warn("❌ 认证失败：Token 无效");
            throw new RuntimeException("认证失败：Token 无效");
        }

        // 获取用户信息
        UserInfoVO user = userService.getUserById(userId);
        if (user == null) {
            log.warn("❌ 认证失败：用户不存在");
            throw new RuntimeException("认证失败：用户不存在");
        }

        // 将用户信息存入 ThreadLocal
        UserContext.setUser(user);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.remove(); // 清理 ThreadLocal
    }
}
